package com.sgx.learning.luban.io.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.ArrayList;
import java.util.List;

public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

    private static List<Channel> channelList = new ArrayList<>();

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelList.add(channel);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        System.out.println("收到消息:" + msg);
        channelList.forEach(temp ->{
            if(temp != channelHandlerContext.channel()) {
                temp.writeAndFlush("[客户端 " + channelHandlerContext.channel().remoteAddress() + "] 发送消息:" + msg);
            } else {
                temp.writeAndFlush("[自己] 发送消息:" + msg);
            }
        });
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        ByteBuf buf = Unpooled.copiedBuffer("HelloClient",CharsetUtil.UTF_8);
//        ctx.writeAndFlush(buf);
    }

}